package com.mouse.remind;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import com.umeng.analytics.MobclickAgent;
import com.ze.commontool.NetHelper;
import com.ze.commontool.SoundPlayer;
import com.ze.commontool.ToastUtil;
import com.ze.familyday.familyphotoframesquare.PhotoFrameActivity;
import com.ze.familyday.familyphotoframesquare.R;
import com.ze.familydayverpm.userinfo.UserInfoManager;



import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.media.MediaPlayer.OnErrorListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Vibrator;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.GestureDetector;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.GestureDetector.OnGestureListener;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.widget.AbsListView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.MediaController;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.VideoView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.ImageView.ScaleType;

public class AlarmDialogActivity extends Activity implements OnClickListener{
	private TextView tvTime;
	private TextView tvDate;
	private RelativeLayout rlAlarmBg;
	private RelativeLayout llLlContent;	
	//private LinearLayout llPerson;
	//private TextView tvPerson;
	//private ImageView ivIvCover;
	private TextView tvTvSubject;
	//private LinearLayout llLlBelow;
	//private LinearLayout llBelow2;
	//private Button btnBtClose;
	//private ProgressBar progressBar;
	
	private MediaPlayer mediaPlayer;
	private Vibrator vibrator;
	
	private String id;
	private String uid;
	private SharedPreferences share;
	private MapBean calendarinfo;
	private AlarmModel alarm;
	//private UserInfo userInfo;
	private Context context;
	String m_auth = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        MobclickAgent.onError(this);
        //MobclickAgent.update(this); 
        //MobclickAgent.setUpdateOnlyWifi(false);
        final Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
				| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
				| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.alarm_dialog);
        context = this;
        if (UserInfoManager.getInstance(context).getItem("m_auth") != null) {
        	m_auth = UserInfoManager.getInstance(context).getItem("m_auth").getValue();
		}
        id = getIntent().getStringExtra("id");
        uid = getIntent().getStringExtra("uid");
        if (uid == null) {
			uid = "";
		}
        if (UserInfoManager.getInstance(context).getItem("uid") != null) {
			uid = UserInfoManager.getInstance(context).getItem("uid").getValue();
		}
        initView();
        initEvent();
        startAlarm();
    }
    
    private void initEvent() {
    	//tvTime.setOnClickListener( this );
    	//llLlContent.setOnClickListener( this );
    	//ivIvCover.setOnClickListener( this );
    	//tvTvSubject.setOnClickListener( this );
    	//llLlBelow.setOnClickListener( this );
    	//llBelow2.setOnClickListener( this );
    	//btnBtClose.setOnClickListener( this );
    	
    	TelephonyManager telephonyManager = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);

		PhoneStateListener phoneStateListener = new PhoneStateListener() {
			@Override
			public void onCallStateChanged(int state, String incomingNumber) {
				switch (state) {
				case TelephonyManager.CALL_STATE_RINGING:
					Log.d(getClass().getSimpleName(), "Incoming call: "
							+ incomingNumber);
					try {
						if (mediaPlayer != null && mediaPlayer.isPlaying()) {
							mediaPlayer.pause();
						}
					} catch (IllegalStateException e) {

					}
					break;
				case TelephonyManager.CALL_STATE_IDLE:
					Log.d(getClass().getSimpleName(), "Call State Idle");
					try {
						if (mediaPlayer != null) {
							mediaPlayer.start();
						}
					} catch (IllegalStateException e) {

					}
					break;
				}
				super.onCallStateChanged(state, incomingNumber);
			}
		};

		telephonyManager.listen(phoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);
	}

	private void initView() {
		rlAlarmBg = (RelativeLayout) findViewById(R.id.rlAlarmBg);
		rlAlarmBg.setOnClickListener(this);
		tvTime = (TextView) findViewById( R.id.tvTime );
		tvDate = (TextView) findViewById(R.id.tvDate);
		llLlContent = (RelativeLayout) findViewById( R.id.llContent );
		//llPerson = (LinearLayout) findViewById( R.id.llPerson );
		//tvPerson = (TextView) findViewById( R.id.tvPerson );
		//ivIvCover = (ImageView) findViewById( R.id.ivCover );
		tvTvSubject = (TextView) findViewById( R.id.tvSubject );
		//llLlBelow = (LinearLayout) findViewById( R.id.llBelow );
		/*llBelow2 = (LinearLayout) findViewById( R.id.llBelow2 );
		btnBtClose = (Button) findViewById( R.id.btClose );
		progressBar = (ProgressBar)findViewById( R.id.progressBar );*/
        
        share = getSharedPreferences(Constant.SHARED_NAME, Context.MODE_PRIVATE);
        /*String imagesrc = share.getString("Imagesrc", "");
        Bitmap tempBMP = WebTools.getBitmapByUrlCache(AlarmDialogActivity.this, imagesrc);
        if (tempBMP != null) {
        	ivIvCover.setScaleType(ScaleType.CENTER_CROP);
			ivIvCover.setImageBitmap(tempBMP);
		}*/
        
        calendarinfo = (MapBean)getIntent().getSerializableExtra("calendarinfo");
        alarm = (AlarmModel) getIntent().getSerializableExtra("alarm");
        if (calendarinfo != null) {
        	setViewData(calendarinfo);
		}else if (alarm != null) {
			id = alarm.getAlarmid();
        	setViewData(alarm);
		}else {
			new GetAlarmTask().execute();
		}
    }
	
	private void startAlarm() {
		String ringtonePath = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM).toString();
		boolean isTime = getIntent().getBooleanExtra("isTime", false);
		
		if (alarm!= null && !ringtonePath.equals("") && isTime) {
			if (true) {
				vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
				long[] pattern = { 1000, 200, 200, 200 };
				vibrator.vibrate(pattern, 0);
			}
			
			//Log.v("mouse", "播放声音！");
			//设置音量为12
			AudioManager am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
			am.setStreamVolume(AudioManager.STREAM_MUSIC, 
					12, AudioManager.FLAG_ALLOW_RINGER_MODES);
			SoundPlayer.play(AlarmDialogActivity.this, R.raw.remind_sound);
			/*mediaPlayer = new MediaPlayer();
			try {
				mediaPlayer.setVolume(1.0f, 1.0f);
				mediaPlayer.setDataSource(this,
						Uri.parse(ringtonePath));
				mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
				mediaPlayer.setLooping(true);
				mediaPlayer.prepare();
				mediaPlayer.start();

			} catch (Exception e) {
				mediaPlayer.release();
			}*/
		}

	}
	
	private void setViewData(MapBean calendarinfo) {
		String uid = UserInfoManager.getInstance(context).getItem("uid").getValue();
		if (calendarinfo != null) {
        	tvTime.setText(calendarinfo.get("time"));
			tvTvSubject.setText(calendarinfo.get("subject"));
			
			String calendarto = calendarinfo.get("calendarto");
			if (!calendarto.equals("") && !calendarto.equals("[]")) {
				List<MapBean> calendartoMap = JsonParse.parseToListMap(calendarto);
				if (calendartoMap!=null && calendartoMap.size()>0) {
					String names = "";
					int size = calendartoMap.size();
					int i=0;
					for (MapBean mapBean : calendartoMap) {
						names = names+mapBean.get("name")+ ((i!=size-1)?",":"");
						if (uid.equals(mapBean.get("uid"))) {
							//llLlBelow.setVisibility(View.VISIBLE);
						}
						i++;
					}
					//llPerson.setVisibility(View.VISIBLE);
					//tvPerson.setText(names);
					System.out.println("names:" + names);
				}
			}
			if (uid.equals(calendarinfo.get("uid"))) {
				//llBelow2.setVisibility(View.VISIBLE);
			}
			String year = calendarinfo.get("year");
			String month = calendarinfo.get("month");
			String day = calendarinfo.get("day");
			int wday = calendarinfo.getInt("wday");
			String time = calendarinfo.get("time");
			String[] dayOfWeeks = getResources().getStringArray(R.array.dayofweek);
			
			String repeatday = calendarinfo.get("repeatday");
			if (repeatday.equals(AlarmModel.Repeatday.ONLY_ONECE)) {
				//tvTime.setText(year+"-"+month+"-"+day+" "+time);
				tvDate.setText(year + "年" + month + "月" + day + "日");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_DAY)) {
				//tvTime.setText("每天"+time);
				tvDate.setText("每天");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_WEEK)) {
				//tvTime.setText("每"+dayOfWeeks[wday]+time);
				tvDate.setText("每"+dayOfWeeks[wday]);
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_MONTH)) {
				//tvTime.setText("每月"+day+"日"+time);
				tvDate.setText("每月"+day+"日");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_YEAR)) {
				//tvTime.setText("每年"+month+"-"+day+" "+time);
				tvDate.setText("每年"+month+"-"+day + "日");
			}
		}
	}
	
	private void setViewData(AlarmModel alarm) {
		String uid = UserInfoManager.getInstance(context).getItem("uid").getValue();
		if (alarm != null) {
        	tvTime.setText(alarm.getTime());
			tvTvSubject.setText(alarm.getSubject());
			ArrayList<User> userList = alarm.getUserList();  
			if (userList != null && userList.size() > 0) {
				String names = "";
				int size = userList.size();
				int i=0;
				for (User user : userList) {
					names = names+user.getName()+ ((i!=size-1)?",":"");
					if (uid.equals(user.getUid())) {
						//llLlBelow.setVisibility(View.VISIBLE);
					}
					i++;
				}
				//llPerson.setVisibility(View.VISIBLE);
				//tvPerson.setText(names);
			}
			if (uid.equals(alarm.getUid())) {
				//llBelow2.setVisibility(View.VISIBLE);
			}
			String year = alarm.getYear();
			String month = alarm.getMonth();
			String day = alarm.getDay();
			int wday = Integer.parseInt(alarm.getWday());
			String time = alarm.getTime();
			String[] dayOfWeeks = getResources().getStringArray(R.array.dayofweek);
			
			String repeatday = alarm.getRepeatday();
			if (repeatday.equals(AlarmModel.Repeatday.ONLY_ONECE)) {
				//tvTime.setText(year+"-"+month+"-"+day+" "+time);
				tvDate.setText(year + "年" + month + "月" + day + "日");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_DAY)) {
				//tvTime.setText("每天"+time);
				tvDate.setText("每天");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_WEEK)) {
				//tvTime.setText("每"+dayOfWeeks[wday]+time);
				tvDate.setText("每"+dayOfWeeks[wday]);
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_MONTH)) {
				//tvTime.setText("每月"+day+"日"+time);
				tvDate.setText("每月"+day+"日");
			}else if (repeatday.equals(AlarmModel.Repeatday.ONECE_OF_YEAR)) {
				//tvTime.setText("每年"+month+"-"+day+" "+time);
				tvDate.setText("每年"+month+"-"+day + "日");
			}
		}
	}
	
	@Override
	public void onClick(View v) {
		/*if (v == btnBtClose) {
			finish();
			//overridePendingTransition(R.anim.zoom_enter,R.anim.zoomout_exit);
		}else if (v == llLlBelow) {
			finish();
		}else if (v == llBelow2) {
			Database.init(getApplicationContext());
			Database.deleteEntryByAlarmid(id);
			Intent serviceIntent = new Intent(getApplicationContext(),AlarmBootReceiver.class);
			sendBroadcast(serviceIntent, null);
			
			new postDeleteNoticeTask(id).execute();
		}
		else*/ if (v == rlAlarmBg) {
			Database.init(getApplicationContext());
			Database.deleteEntryByAlarmid(id);
			Intent serviceIntent = new Intent(getApplicationContext(),AlarmBootReceiver.class);
			sendBroadcast(serviceIntent, null);
			
			new postDeleteNoticeTask(id).execute();
		}
		overridePendingTransition(R.anim.zoom_enter,R.anim.zoomout_exit);
	}
    
	
	class GetAlarmTask extends AsyncTask<String, Void, String>{
		String resultStr;  //原始数据
		HashMap<String, String> tempMap;
		protected void onPreExecute() {
			//showLoadingDialog();
			super.onPreExecute();
		}
		
		protected String doInBackground(String... params) {
			//resultStr = WebTools.getDateByHttpClient(getNoticeDetail(id));
			resultStr = NetHelper.getResponByHttpClient(getNoticeDetail(id));
			if(resultStr != null && !"".equals(resultStr.trim())){
				try {
					JSONObject resultData = new JSONObject(resultStr);
					int error = resultData.getInt("error");
					if(error == 0){
						JSONObject data = resultData.getJSONObject("data");
						
						tempMap = new HashMap<String, String>();
						tempMap.put("id", data.getString("id"));
						tempMap.put("subject", data.getString("subject").replaceAll("&nbsp;", " "));
						tempMap.put("time", data.getString("time"));
						tempMap.put("year", data.getString("year"));
						tempMap.put("month", data.getString("month"));
						tempMap.put("day", data.getString("day"));
						tempMap.put("wday", data.getString("wday"));
						tempMap.put("uid", data.getString("uid"));
						tempMap.put("repeatday", data.getString("repeatday"));
						tempMap.put("idtype", data.getString("idtype"));
						tempMap.put("calendarto", data.getString("calendarto"));
						
					}
				}catch (Exception e) {
					e.printStackTrace();
				}
			}
			return null;
		}

		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			//hideLoadingDialog();
			if (tempMap != null && tempMap.size()>0) {
				calendarinfo = new MapBean();
				calendarinfo.setMap(tempMap);
				setViewData(calendarinfo);
				/*tvTime.setText(tempMap.get("time"));
				tvTvSubject.setText(tempMap.get("subject"));*/
			}
			
		}
	}
	
	class postDeleteNoticeTask extends AsyncTask<Integer, Integer, String>{
		String jsonStr;
		String id;
		
		public postDeleteNoticeTask(String id) {
			this.id = id;
		}


		@Override
		protected void onPreExecute() {
			//ToastUtil.show(context, "删除");
			super.onPreExecute();
		}


		@Override
		protected String doInBackground(Integer... params) {
			jsonStr = postDeleteNotice(id);
			return null;
		}
		
		protected void onPostExecute(String str){
			if(jsonStr!= null && !"".equals(jsonStr.trim())){
				try{
					JSONObject result = new JSONObject(jsonStr);
					if(result.getInt("error") == 0){
						//ToastUtil.show(context, "删除提醒成功！");
						finish();
					}else {
						//ToastUtil.show(context, result.getString("msg"));
					}
				}catch(Exception e){
					e.printStackTrace();
				}
			}else {
				TipWinShow.showUploadFailToast(context);
			}
		}
	}
	
	private String postDeleteNotice(String id){
		
		HashMap<String, String> map = new HashMap<String, String>();
	    map.put("id", id);
		map.put("m_auth", m_auth);
		
		List<NameValuePair> requestList = new ArrayList<NameValuePair>();
		NameValuePair item;
		
		Set<String> keySet = map.keySet();
		for (String key : keySet) {
			String value = map.get(key);
			item = new BasicNameValuePair(key, value);
			requestList.add(item);
		}
		
		//return WebTools.post(Urls.getDeleteNotice(), requestList);
		return NetHelper.post(Urls.getDeleteAlarm(), requestList);
	}

	
	/*private void showLoadingDialog(){
  		if (progressBar == null) {
  			return ;
  		}
  		progressBar.setVisibility(View.VISIBLE);
  	}*/
  	
  	/*private void hideLoadingDialog(){
  		if (progressBar != null && progressBar.isShown()) {
  			progressBar.setVisibility(View.GONE);
  		}
  	}*/
  	
	@Override
	protected void onDestroy(){
		try {
			if (vibrator != null)
				vibrator.cancel();
		} catch (Exception e) {

		}
		try {
			if (mediaPlayer != null){
				mediaPlayer.stop();
				mediaPlayer.release();
			}
		} catch (Exception e) {

		}
		super.onDestroy();
	}
	
	//加入友盟统计代码
    public void onResume() {
    	super.onResume();
    	MobclickAgent.onResume(this);
    	/*AlarmAlertWakeLock.acquire(context);
		StaticKeyguardLock.disabledKeyguard(context);*/
    }
    
    public void onPause() {
    	super.onPause();
    	MobclickAgent.onPause(this);
    	//StaticWakeLock.lockOff(this);
    	AlarmAlertWakeLock.release();
    	StaticKeyguardLock.enabledKeyguard();
    }
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		finish();
		overridePendingTransition(R.anim.zoom_enter,R.anim.zoomout_exit);
    	return false;
    }

	/**
	 * 2.58编辑提醒显示接口
	 * @param id               提醒的主键id
	 * @param m_auth:          API密钥, 由登录后返回的，客户端需要存储,每次调用接口需要使用此参数发到服务器
	 * 
	 * @return
	 * */
	public String getNoticeDetail(String id) {
		return new StringBuffer().append(NetHelper.HOST)
				.append("/dapi/cp.php?ac=calendar&op=editcalendar")
				.append("&id=").append(id)
				.append("&m_auth=").append(m_auth)
				.toString();
	}

}